﻿using System;
using System.Collections.Generic;
using System.Text;
using agsXMPP.protocol.x.muc;
using agsXMPP;
using agsXMPP.protocol.client;
using log4net.Util;
namespace log4net.Extensions.Appender.XMPP
{
    public class XMPPAppenderConnection
    {
        public XmppClientConnection Conn { get; private set; }
        public MucManager MucManager { get; private set; }

        internal XMPPAppenderConnection(XmppClientConnection conn)
        {
            if (null == conn) throw new ArgumentNullException("conn", "conn cannot be null.");
            this.Conn = conn;
            this.Conn.OnLogin += new ObjectHandler(Conn_OnLogin);    
        }

        void Conn_OnLogin(object sender)
        {
            this.MucManager = new MucManager(this.Conn);
        }

        private static object _ConnLock = new object();
        private static System.Collections.Hashtable _ConnLookup = new System.Collections.Hashtable();

        internal static XMPPAppenderConnection GetConnection(string Server, int Port, string UserName, string Password)
        {
            UriBuilder builder = new UriBuilder();
            builder.Scheme = "xmpp";
            builder.Port = Port;
            builder.Host = Server;
            builder.Password = Password;
            builder.UserName = UserName;

            System.Uri uri = builder.Uri;

           
            XMPPAppenderConnection conn = (XMPPAppenderConnection)_ConnLookup[uri];

            if (null != conn)
            {
                return conn;
            }
            lock (_ConnLock)
            {
                if (LogLog.IsDebugEnabled) LogLog.Debug("XMPPAppenderConnection.GetConnection - Creating new connection to " + Server + ":" + Port);
                XmppClientConnection clientConn = new XmppClientConnection(Server, Port);
                clientConn.Open(UserName, Password, Environment.MachineName);

                conn = new XMPPAppenderConnection(clientConn);
                _ConnLookup.Add(uri, conn);
            }
            return conn;
        }

        
    }
}
